//
//  WBUserModel.swift
//  ZWWEIBO
//
//  Created by xzw on 2018/4/6.
//  Copyright © 2018年 xzw. All rights reserved.
//

import UIKit

private let userPath:NSString = "userModel.json"

@objcMembers
class WBUserModel: NSObject {

    //登陆令牌
    var access_token : String? //= "2.00WPx_BHYHj26C58e09fbe44VdaS9C"
    
    //用户uid
    var uid : String?
    
    //用户昵称
    var screen_name : String?
    
    //用户头像地址
    var avatar_large : String?
    
    //令牌过期时间，开发者5年，适用者三天，单位秒
    var expires_in : TimeInterval = 0 {
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate : Date?
    
    
    override init() {
        super.init()
        
        //1.从磁盘加载用户信息
       guard let path = userPath.cz_appendDocumentDir(),
       let data = NSData(contentsOfFile: path),
       let dic = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:Any] else {
            return
        }
        
        //2.字典转模型赋值
        yy_modelSet(with: dic ?? [:])
        print("模型赋值成功 \(self)")
        
        //3.判断token是否过期
        if expiresDate?.compare(Date()) == .orderedAscending {//过期
            access_token = nil
            uid = nil
            //删除缓存文件
           try? FileManager.default.removeItem(atPath: userPath as String)
        }
    
    }
    
    
    override var description: String{
        return yy_modelDescription()
    }
    
    //保存模型到沙盒
    func saveUserModel(){
    
        //1.模型转字典
        var dic = self.yy_modelToJSONObject() as? [String : Any] ?? [:]
        
       //2.删除expires_in key
       dic.removeValue(forKey: "expires_in")
        
       //3.字典序列化
        guard  let data = try? JSONSerialization.data(withJSONObject: dic, options: []),
               let path = userPath.cz_appendDocumentDir() else  {
               return
        }
        
       //4.写入文件
       (data as NSData).write(toFile: path, atomically: true)
        print("用户模型保存成功 \(path)")
    }
}
